import { loginAPI, getProfileAPI } from '@/apis/user'
import { getCookie, setCookie, removeCookie } from '@/utils/auth'
import { TOKEN_KEY } from '@/constants/KEY'
export default {
  namespaced: true,
  state: () => {
    return {
      token: getCookie(TOKEN_KEY) || '',
      profile: {}
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      // 本地存一份
      setCookie(TOKEN_KEY, token)
    },
    clearUserInfo(state) {
      // 清除Token
      state.token = ''
      state.profile = {}
      removeCookie(TOKEN_KEY)
    },
    setProfile(state, profile) {
      state.profile = profile
    }
  },
  actions: {
    async doLogin(ctx, { username, password }) {
      // 1. 调用接口
      const res = await loginAPI({ username, password })
      // 2. 提交mutation
      ctx.commit('setToken', res.data.token)
    },
    async getProfile(ctx) {
      const res = await getProfileAPI()
      ctx.commit('setProfile', res.data)
      return res.data.permissions
    }
  }
}
